package com.useeinfo.oa.modules.base.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.AnalysisObjectList;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.dao.AreaDao;
import com.useeinfo.oa.modules.base.entity.Area;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Auther: xudong.sun
 * @Date: 2018/12/7 15:50
 * @Description:
 */
@Service
public class AreaBiz extends CrudBiz<AreaDao, Area> {

    //同一节点下名称不能重复，不同节点下可以重复
    public Boolean existArea(Area area, Long enterpriseId) {
        if (StringUtils.isBlank(area.getAreaName())||StringUtils.isBlank(area.getAreaCode())) {
            return true;
        }
        QueryParam queryParam1 = new QueryParam();
        queryParam1.getSqlMap().put("enterpriseId", enterpriseId+"");
        queryParam1.getSqlMap().put("areaName", area.getAreaName());
        queryParam1.getSqlMap().put("areaCode", area.getAreaCode());
        queryParam1.getSqlMap().put("parentIds", area.getParentIds());
        List<Area> areaList1 = findList(queryParam1);
        QueryParam queryParam2 = new QueryParam();
        queryParam2.getSqlMap().put("enterpriseId", enterpriseId+"");
        queryParam2.getSqlMap().put("areaCode", area.getAreaCode());
        queryParam1.getSqlMap().put("parentIds", area.getParentIds());
        List<Area> areaList2 = findList(queryParam2);
        if (area.getId() == null) {//新增，查该节点下没有这个名称
            return CollectionUtils.isNotEmpty(areaList1)||CollectionUtils.isNotEmpty(areaList2);
        } else {
            return (!((areaList1.size() == 1 && areaList1.get(0).getId().equals(area.getId())) || areaList1.size() == 0))
                    ||
                    (!((areaList2.size() == 1 && areaList2.get(0).getId().equals(area.getId())) || areaList2.size() == 0));
        }
    }

    /**
     * 根据名称判断是否有该设备分类(有返回 没有返回NULL)
     *
     * @param enterpriseId
     * @return
     */
    public Area getAreaByName(String areaName,String enterpriseId) {
        if(StringUtils.isBlank(areaName)||StringUtils.isBlank(enterpriseId)){
            return null;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", enterpriseId+"");
        queryParam.getSqlMap().put("areaName", areaName);
        List<Area> areaList = this.findList(queryParam);
        if(CollectionUtils.isNotEmpty(areaList)){
            return areaList.get(0);
        }
        return null;
    }

    /**
     * 查询该区域有没有子区域（查询有没有儿子）
     * @param parentId
     * @return
     */
    public Boolean existHaveSon(Long parentId) {
        Area area = this.findModel(parentId);
        if(area==null){
            return false;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("parentId",parentId+"");
        List<Area> areaList = this.findList(queryParam);
        return CollectionUtils.isNotEmpty(areaList);
    }

    /**
     * 查询直属下级
     * @param parentId
     * @return
     */
    public List<Area> findSonList(Long parentId) {
        List<Area> areaList = new ArrayList<>();
        if(parentId==null||parentId<1L){
            return areaList;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("parentId",parentId+"");
        areaList = this.findList(queryParam);
        return  areaList;
    }

    /**
     * 递归变更
     * @param parentId
     * @return
     */
    public void recursionChangeParentIds(Long parentId) {
        Area parentArea = this.findModel(parentId);
        if(parentArea!=null){
            List<Area> list = findSonList(parentId);
            if(CollectionUtils.isNotEmpty(list)){
                for (Area sonArea:list){
                    sonArea.setRootId(parentArea.getRootId());
                    sonArea.setLvl((parentArea.getLvl()!=null?parentArea.getLvl():0)+1);
                    sonArea.setParentIds((StringUtils.isEmpty(parentArea.getParentIds())?"":(parentArea.getParentIds()+","))+parentArea.getId());
                    this.addOrUpdate(sonArea);
                    recursionChangeParentIds(sonArea.getId());
                }
            }
        }
    }


    /**
     * 查询区域完全树形json
     * @param parentId
     * @return
     */
    public JSONArray findTreeData(Long parentId, Long enterpriseId) {
        JSONArray result = new JSONArray();
        QueryParam queryParam = new QueryParam();
        if(enterpriseId!=null){
            queryParam.getSqlMap().put("enterpriseId", enterpriseId+"");
        }
        if(parentId!=null){
            queryParam.getSqlMap().put("parentId", parentId+"");
        }else{
            queryParam.getSqlMap().put("bigParent", "随便写点什么");
        }
        List<Area> areaList = this.findList(queryParam);
        if(CollectionUtils.isNotEmpty(areaList)){
            for (Area area:areaList){
                JSONObject json = new JSONObject();
                json.put("id",area.getId());
                json.put("areaName",StringConverters.null2String(area.getAreaName()));
                json.put("areaCode",StringConverters.null2String(area.getAreaCode()));
                result.add(json);
            }
        }
        return findChildrenTreeData(result);
    }


    /**
     * 递归查询下级json
     * @param array
     * @return
     */
    public JSONArray findChildrenTreeData(JSONArray array) {
        for (int i = 0; i < array.size(); i++) {
            JSONObject json = array.getJSONObject(i);
            JSONArray childrenArray = new JSONArray();
            json.put("childrenArray",childrenArray);
            json.put("childrenCount",0);
            Long parentId = json.getLong("id");
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("parentId", parentId+"");
            List<Area> areaList = this.findList(queryParam);
            if(CollectionUtils.isNotEmpty(areaList)){
                for (Area area:areaList){
                    JSONObject childrenJson = new JSONObject();
                    childrenJson.put("id",area.getId());
                    childrenJson.put("areaName",StringConverters.null2String(area.getAreaName()));
                    childrenJson.put("areaCode",StringConverters.null2String(area.getAreaCode()));
                    childrenArray.add(childrenJson);
                }
                findChildrenTreeData(childrenArray);
                json.put("childrenArray",childrenArray);
                json.put("childrenCount",childrenArray.size());
            }
        }
        return array;
    }

    public List<Area> hqlExcute(String hql){
        return dao.hqlExcute(hql);
    }

    /**
     * 获取区域
     */
    public JSONArray getAreaListByEnterprise(Map<String, Object> dataMap) {
        JSONArray jsonArray = new JSONArray();
        List objects = dao.getAreaListByEnterprise(dataMap);
        if (CollectionUtils.isNotEmpty(objects)) {
            try {
                for (Object object : objects) {
                    net.sf.json.JSONArray j = net.sf.json.JSONArray.fromObject(object);
                    jsonArray.add(AnalysisObjectList.getJsonString(j, 1));
                }
            } catch (Exception e) {
                logger.info("数据异常");
            }
        }
        return jsonArray;
    }

}
